import json
import requests
from backend.config import XUNFEI_API_CONFIG


class XunfeiLLM:
    def __init__(self):
        self.api_key = XUNFEI_API_CONFIG['api_key']
        self.url = XUNFEI_API_CONFIG['url']
        self.chat_history = []
        self.max_retries = 3

    def get_answer(self, messages):
        """调用讯飞API获取回答（使用Bearer Token方式）"""
        headers = {
            'Authorization': self.api_key,
            'Content-Type': 'application/json'
        }
        body = {
            "model": "Lite",
            "user": "user_id",
            "messages": messages,
            "stream": True
        }
        full_response = ""

        try:
            response = requests.post(
                self.url,
                headers=headers,
                json=body,
                stream=True,
                timeout=(10, 30)
            )

            if response.status_code != 200:
                error_msg = f"API请求失败，状态码: {response.status_code}，响应内容: {response.text}"
                print(error_msg)
                return error_msg

            for chunk in response.iter_lines():
                if chunk:
                    chunk_str = chunk.decode('utf-8')
                    if chunk_str.startswith('data:'):
                        data = chunk_str[5:].strip()
                        if data == '[DONE]':
                            break
                        try:
                            chunk_json = json.loads(data)
                            content = chunk_json.get('choices', [{}])[0].get('delta', {}).get('content', '')
                            if content:
                                full_response += content
                        except json.JSONDecodeError as e:
                            print(f"JSON解析错误: {e}, 原始数据: {data}")
                            continue
            return full_response
        except Exception as e:
            error_msg = f"调用模型失败：{str(e)}"
            print(error_msg)
            return error_msg

    def generate_test_cases(self, intent_type, count=10):
        """生成测试用例"""
        prompt = f"生成{count}个关于'{intent_type}'意图的中文测试用例"
        messages = [{"role": "user", "content": prompt}]
        response = self.get_answer(messages)
        test_cases = response.split('\n')[:count]
        return [tc.strip() for tc in test_cases if tc.strip()]